'''
Created on 30.03.2010

@author: philipp
'''
import os
from sys import argv

mstest_dir = "E:\\HSLU\\6. Semester\\BDA\\SVN\\Sourcen\\GuiaPrototype\\GuiaTest"
nunit_dir = "E:\\HSLU\\6. Semester\\BDA\\SVN\\Sourcen\\GuiaPrototype\\NUnitTests"
mstest_namespace = "GuiaTest"
nunit_namespace = "NUnitTests" 
mstest_using = "Microsoft.VisualStudio.TestTools.UnitTesting"
nunit_using = "NUnit.Framework"
mstest_test_class = "[TestClass"
nunit_test_class = "[TestFixture"
mstest_test_initialize = "[TestInitialize"
nunit_test_initialize = "[SetUp"
mstest_test_cleanup = "[TestCleanup"
nunit_test_cleanup = "[TearDown"
mstest_test_method = "[TestMethod"
nunit_test_method = "[Test"
mstest_test_context_instance = "private TestContext testContextInstance;"
    
    
def migrate_file(old_file,new_file):
    print("Migrating",old_file.name,"to",new_file.name)
    lines = old_file.readlines()
    ctr = 0
    lines[0] = lines[0].lstrip()
    i=0
    while(i < len(lines)):
        line = lines[i]
        newline = line
        if contains(line,mstest_namespace):
            newline = "namespace " + nunit_namespace
        elif contains(line,mstest_using):
            newline = line.replace(mstest_using,nunit_using)
        elif contains(line,mstest_test_class):
            newline = line.replace(mstest_test_class,nunit_test_class)
        elif contains(line,mstest_test_initialize):
            newline = line.replace(mstest_test_initialize,nunit_test_initialize)
        elif contains(line,mstest_test_cleanup):
            newline = line.replace(mstest_test_cleanup,nunit_test_cleanup)
        elif contains(line,mstest_test_method):
            newline = line.replace(mstest_test_method,nunit_test_method)
        elif contains(line,mstest_test_context_instance):
            par_counter = 0
            ctr = i
            while(par_counter < 3):
                line = lines[ctr]
                if contains(line,"}"):
                    par_counter+=1
                ctr+=1
            i=ctr
            continue
        
        new_file.write(newline)
        i+=1

        
def contains(theString, theQueryValue):
    return theString.find(theQueryValue) > -1

def print_help():
    print("use mstest2nunit.py MSTestDirectory NUnitDirectory")



if __name__ == '__main__':
    if len(argv) != 3:
        print_help()
        exit()
    mstest_dir = argv[1]
    nunit_dir = argv[2]
    print("running migrator...")
    files = os.listdir(mstest_dir)
    for file in files:
        if file.endswith("Test.cs"):
            old_file = open(mstest_dir + "\\" + file,"r")
            new_file = open(nunit_dir + "\\" + file,"w")
            migrate_file(old_file, new_file)
            old_file.close()
            new_file.close()
    print("migrator finished")
